package helper

import (
	"github.com/labstack/echo/v4"
	"net/http"
)

func NewResponse(ctx echo.Context) *Response {
	return &Response{
		ctx: ctx,
	}
}

type Response struct {
	ctx      echo.Context
	HttpCode int
	Code     int         `json:"code"`
	Message  string      `json:"message"`
	Data     interface{} `json:"data,omitempty"`
}

func (r Response) Response() error {
	if r.Code == 0 {
		r.Code = r.HttpCode
	}
	if r.Message == "" {
		r.Message = http.StatusText(r.HttpCode)
	}

	return r.ctx.JSON(r.HttpCode, &ResponseObject{
		Code:    r.Code,
		Message: r.Message,
		Data:    r.Data,
	})
}

// ## status

// ### 100

func (r Response) ResponseContinue() error { // 100
	r.HttpCode = http.StatusContinue

	return r.Response()
}

// ### 200

func (r Response) ResponseOk(data ...interface{}) error { // 200
	r.HttpCode = http.StatusOK
	if len(data) == 1 {
		r.Data = data[0]
	} else if data != nil {
		r.Data = data
	}

	return r.Response()
}
func (r Response) ResponseCreated(data ...interface{}) error { // 201
	r.HttpCode = http.StatusCreated
	if len(data) == 1 {
		r.Data = data[0]
	} else if data != nil {
		r.Data = data
	}

	return r.Response()
}
func (r Response) ResponseAccepted() error { // 202
	r.HttpCode = http.StatusAccepted

	return r.Response()
}

// ### 400

func (r Response) ResponseBadRequest(code int, message ...string) error { // 400
	r.HttpCode = http.StatusBadRequest
	r.Code = code
	if len(message) > 0 {
		r.Message = message[0]
	} else {
		r.Message = GetMessage(r.Code)
	}

	return r.Response()
}
func (r Response) ResponseStatusUnauthorized() error { // 401
	r.HttpCode = http.StatusUnauthorized

	return r.Response()
}
func (r Response) ResponseForbidden() error { // 403
	r.HttpCode = http.StatusForbidden

	return r.Response()
}
func (r Response) ResponseNotFound() error { // 404
	r.HttpCode = http.StatusNotFound

	return r.Response()
}
